package com.onpositive.queryeditor.util;

import java.util.Arrays;

import org.eclipse.jface.viewers.ContentViewer;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;

/**
 * Provides some basic Drag&Drop support
 * @author 32kda
 *
 */
public class DndUtil
{
	/**
	 * Adds simple text drag source to a viewer
	 * This drag source has a {@link TextTransfer} and uses value given by viewer's {@link ILabelProvider}, as a data for drag
	 * If multipple elements are selected in viewer, their titles will be separated by '\n'
	 * @param viewer {@link ContentViewer} to add drag source to
	 */
	public static void addTextDragSource(final ContentViewer viewer)
	{
		Transfer[] types = new Transfer[] { TextTransfer.getInstance() };
		DragSource dragSource;
		Object oldSource = viewer.getControl().getData(DND.DRAG_SOURCE_KEY);
		if (oldSource != null)
		{
			dragSource = (DragSource) oldSource;
			Transfer[] transfer = dragSource.getTransfer();
			for (int i = 0; i < transfer.length; i++)
			{
				if (transfer[i] instanceof TextTransfer)
					return; //already has it
			}
			Transfer[] newTransfers = Arrays.copyOf(transfer,transfer.length + 1);
			newTransfers[newTransfers.length - 1] = TextTransfer.getInstance();
			dragSource.setTransfer(newTransfers);
		}
		else
		{
			dragSource = new DragSource(viewer.getControl(), DND.DROP_COPY);
			dragSource.setTransfer(types);
		}
		dragSource.addDragListener(new DragSourceListener()
		{
			
			public void dragStart(DragSourceEvent event)
			{
				if (!viewer.getSelection().isEmpty())
					event.doit = true;
			}
			
			public void dragSetData(DragSourceEvent event)
			{
				if (!TextTransfer.getInstance().isSupportedType(event.dataType))
					return;
				ISelection selection = viewer.getSelection();
				if (selection instanceof IStructuredSelection)
				{
					StringBuilder builder = new StringBuilder();
					Object[] items = ((IStructuredSelection) selection).toArray();
					ILabelProvider labelProvider = (ILabelProvider)viewer.getLabelProvider();
					for (int i = 0; i < items.length; i++)
					{
						builder.append(labelProvider.getText(items[i]));
						if (i < items.length - 1)
							builder.append('\n');
					}
					event.data = builder.toString();
				}
			}
			
			public void dragFinished(DragSourceEvent event)
			{
			}
		});
	}

}
